<?php
namespace app\yunda\admin;

use app\common\builder\ZBuilder;
use app\yunda\model\Cash as CashModel;
use think\Db;

/**
 * Class Category用户提现记录
 * @package app\yunda\admin
 */
class Cash extends Base{

    public function index()
    {
//        halt(APP_PATH.'yunda/cert/apiclient_cert.pem');
        // 获取查询和排序规则
        $map = $this->getMap();
        $order = $this->getOrder();
        $map['dp_yd_cash.delete_time']=NULL;
        $data = Db::view('dp_yd_cash',true)
             ->view('yd_user',['nickname'],'yd_user.openid=dp_yd_cash.openid')
            ->where($map)
            ->order($order)
            ->order('dp_yd_cash.id desc')
            ->paginate()->each(function($item){
                $arr=['未知','微信','支付宝'];
                $arr1=['否','是'];
                $item['type']=$arr[$item['type']];
                $item['is_tx']=$arr1[$item['is_tx']];
                return $item;
            });
//        halt($data);
        return ZBuilder::make('table')
            ->setTableName('yd_cash')
            ->addColumns([
                ['id','id'],
                ['openid','openid'],
                ['name','姓名'],
                ['phone','电话'],
                ['type','账号类型'],
                ['account','账号'],
                ['money','提现金额'],
                ['is_tx','是否提现'],
                ['status','审核','status','',['待审核:danger','通过:info','拒绝:warning']],
                ['create_time','创建时间','datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->setRowList($data)
            ->addRightButton('edit',[],[])
            ->addFilter(['nickname'=>'yd_user'])
            ->addTimeFilter('dp_yd_cash.create_time') // 添加时间段筛选
            ->fetch();
    }

    public function edit($id=null){
        if($this->request->isPost()){
            $data = request()->post();
            $one=CashModel::get($data['id']);
            if($one['is_tx']==1) $this->error('该条提现申请已经通过');
            if($data['status']==1){
//                $tx=$this->tixian($id);//通过提现
//                if($tx['code']==0) $this->error($tx['msg']);
                $data['is_tx']=1;
            }
            CashModel::update($data);
            $this->success('保存成功', null, '_parent_reload');
        }
        $data = CashModel::get($id);
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],  // 多增加一个影藏ID 即可
                ['radio','status','审核','',['待审核','通过','拒绝']],
            ])
            ->setFormData($data)
            ->fetch();
    }

    ////////////////打款//////////////////////

    //提现
    public function tixian($id)
    {
        $usercash=CashModel::get($id);

        $data=array(
            'mch_appid'=>config('weiXin')['appid'],//商户账号appid
            'mchid'=>config('weiXin')['mid'],//商户号
            'nonce_str'=>rand(1111111111,9999999999),//随机字符串
            'partner_trade_no'=>time().rand(11111,99999),//商户订单号
            'openid'=>$usercash['openid'],//用户openid
            'check_name'=>'NO_CHECK',//校验用户姓名选项,
            're_user_name'=>$usercash['name'],//收款用户姓名
            'amount'=>$usercash['money']*100,//金额
            'desc'=>'提现打款',//企业付款描述信息
            'spbill_create_ip'=>get_client_ip(),//Ip地址
        );
        $key=config('weiXin')['key'];///这个就是个API密码。32位的。。随便MD5一下就可以了
        // $key=md5($key);
        $data=array_filter($data);
        ksort($data);
        $str='';
        foreach($data as $k=>$v) {
            $str.=$k.'='.$v.'&';
        }
        $str.='key='.$key;
        $data['sign']=md5($str);
        $xml=$this->arraytoxml($data);
        $url='https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $res=$this->curl($xml,$url);
        $return=$this->xmltoarray($res);
        if($return['result_code']=='SUCCESS'){
            //扣除用户佣金，并加入提现记录表

            $message=['msg'=>'','code'=>1];
        }else{
            if($return['err_code_des']){
                $message=['msg'=>$return['err_code_des'],'code'=>0];
            }else{
                $message=['msg'=>'请检查证书是否上传正确!','code'=>0];
            }
        }
        return $message;
    }


    public function arraytoxml($data){
        $str='<xml>';
        foreach($data as $k=>$v) {
            $str.='<'.$k.'>'.$v.'</'.$k.'>';
        }
        $str.='</xml>';
        return $str;
    }
    public function xmltoarray($xml) {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring),true);
        return $val;
    }
    public function curl($param="",$url) {
        global $_GPC, $_W;
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();                                      //初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);                 //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);           // 增加 HTTP Header（头）里的字段
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        // 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch,CURLOPT_SSLCERT,APP_PATH.'yunda/cert/apiclient_cert.pem'); //这个是证书的位置绝对路径
        curl_setopt($ch,CURLOPT_SSLKEY,APP_PATH.'yunda/cert/apiclient_key.pem'); //这个也是证书的位置绝对路径
        $data = curl_exec($ch);                                 //运行curl
        curl_close($ch);
        return $data;
    }


////////////////打款//////////////////////



}